package com.sdgakj.utils.wechat.common.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpUtil
{
  public static String get(String url)
    throws IOException
  {
    String responseBody = "";
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
      HttpGet httpget = new HttpGet(url);

      ResponseHandler responseHandler = new ResponseHandler()
      {
        public String handleResponse(HttpResponse response)
          throws ClientProtocolException, IOException
        {
          int status = response.getStatusLine().getStatusCode();
          if ((status >= 200) && (status < 300)) {
            HttpEntity entity = response.getEntity();
            return entity != null ? EntityUtils.toString(entity, "utf-8") : null;
          }
          throw new ClientProtocolException("Unexpected response status: " + status);
        }
      };
      responseBody = (String)httpclient.execute(httpget, responseHandler);
    } finally {
      httpclient.close();
    }

    return responseBody;
  }
}